package com.demarc.pesquisas.infraestrutura.util.relatorio;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;

import net.sf.jasperreports.engine.JRParameter;

import com.demarc.pesquisas.infraestrutura.excecao.InfraException;
import com.demarc.pesquisas.infraestrutura.web.jsf.JsfUtil;

public abstract class AbstractPDFRelatorio implements Serializable {

    private Map<String, Object> reportParameters;

    public AbstractPDFRelatorio() {
        this.reportParameters = new HashMap<String, Object>();
    }

    public void generateReportPDF(String reportPath) throws InfraException {

        getReportParameters().put(JRParameter.REPORT_LOCALE,
                FacesContext.getCurrentInstance().getViewRoot().getLocale());
        addCommonParameters();

        ByteArrayOutputStream outputStream =
                PDFReportHelper.exportReportToPdfOutputStream(reportPath, getReportData(),
                        getReportParameters(), getTitle());

        byte[] content = outputStream.toByteArray();
        ReportUtil.prepararRelatorio(getTitle() + ".pdf", content);

        JsfUtil.executarJavascript("openPdfLink();");
    }

    protected final Map<String, Object> getReportParameters() {
        return reportParameters;
    }

    public void setReportParameters(Map<String, Object> reportParameters) {
        this.reportParameters = reportParameters;
    }

    protected void addCommonParameters() {
        // Add any other parameters to the report.
    }

    public abstract String getJasperFileLocation();

    protected abstract List<?> getReportData();

    public abstract String getTitle();
}
